package novel.front.novellist.controller.qr;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by sutong on 2017/11/6.
 */
@Controller
@RequestMapping("wx2")
public class QrController {
    public static final String redirectUrl = "https://www.oloffe.com";
    @RequestMapping(value = "/getQ", method = { RequestMethod.POST, RequestMethod.GET })
    public void getqcode(HttpServletResponse resp,String amount,String state) throws IOException {
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx2b1e2e5faf7855d7&redirect_uri="+redirectUrl+"/wx2/scanQr?amount="+amount+"&response_type=code&scope=snsapi_userinfo&state="+state+"#wechat_redirect";
        if (url != null && !"".equals(url)) {
            ServletOutputStream stream = null;
            try {

                int width = 200;//图片的宽度
                int height = 200;//高度
                stream = resp.getOutputStream();
                QRCodeWriter writer = new QRCodeWriter();
                BitMatrix m = writer.encode(url, BarcodeFormat.QR_CODE, height, width);
                MatrixToImageWriter.writeToStream(m, "png", stream);
            } catch (WriterException e) {
                e.printStackTrace();
            } finally {
                if (stream != null) {
                    stream.flush();
                    stream.close();
                }
            }
        }
    }
}
